var requestSign = require('./requestData.js');
var api = require('./api.js').open_api;
var re = require('./request.js');
var header = getApp().header;
var app = getApp();

export function getTemData(){
  
}

/**
 * url page地址
 * num 选用的跳转方式1-switchTab，2-reLaunch，3-redirectTo，4-navigateTo，5-navigateBack
 * param 参数
 */
export function jumpPage(data){
  let url = data.url;
  let num = data.num;
  let param = data.param;
  for (let item of app.globalData.tab_list){
    item = '/'+item;
    if (url == item){
      num = 1
      break 
    }
  }

  if(param != ''){
    url = url + param;
  }

  switchPage(url, num);

}

function switchPage(url,num){
  switch (num) {
    case 1:
      switchTab(url);
      break;
    case 2:
      reLaunch(url);
      break;
    case 3:
      redirectTo(url);
      break;
    case 4:
      navigateTo(url);
      break;
    case 5:
      navigateBack(url);
      break;
  }  
}

function switchTab(url){
  wx.switchTab({
    url:url,
  })
}

function reLaunch(url){
  wx.reLaunch({
    url: url
  })
}

function redirectTo(url){
  wx.redirectTo({
    url: url
  })
}

function navigateTo(url){
  wx.navigateTo({
    url: url
  })
}

function navigateBack(url){
  wx.navigateBack({
    delta: url
  })
}


/**
 * 邀请码
 */
export function extend_code(){
  let postData = {}
  let datainfo = requestSign.requestSign(postData);
  header.sign = datainfo
  re.request(api.get_qrcode,postData,header).then((res) =>{
    if(res.data.code == 0){
      wx.setStorageSync("extend_code", res.data.data.extend_code);      
    }
  })
  
}

/**
 * 检查手机号是否正确 
 * */
export function checkPhone(phone) {
  var telStr = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;  
  if (!(telStr.test(phone)) ) {
    console.log("手机号码有误，请重填");
    return false;
  }
}


export function checkIdCardNo(idCardNo){
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X 
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (reg.test(idCardNo) === false) {
    wx.showToast({
      title: '身份证号码不正确！',
      icon:'none',
    })    
    return false;
  }   
}


/**
 * 检查手机号是否存在 
 */
export function hasPhone(){
  const that = this;
  const have_mobile = wx.getStorageSync('have_mobile');
  if (have_mobile != true) {    
    return false
  }
}
/**
 * 分销字段设置
 */
export function distributionSet() {
  const that = this;
  let postData = {}
  let datainfo = requestSign.requestSign(postData);
  header.sign = datainfo;
  return new Promise((resolve,reject) =>{
    wx.request({
      url: api.get_distributionSet,
      data: postData,
      header: header,
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        if (res.data.code == 0) {
          let distributionData = res.data.data;
          getApp().globalData.distributionData = distributionData;
          resolve(res);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          })
        }
      },
      fail: (res) => { },
    })
  })
}

/**
 * 分红字段设置
 */
export function bonusSet(){
  const that = this;
  let postData = {}
  let datainfo = requestSign.requestSign(postData);
  header.sign = datainfo;
  return new Promise((resolve, reject) => {
    wx.request({
      url: api.get_bonusSet,
      data: postData,
      header: header,
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        if (res.data.code == 0) {
          let bonusData = res.data.data;
          getApp().globalData.bonusData = bonusData;
          resolve(res);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          })
        }
      },
      fail: (res) => { },
    })
  })
}


/**
 * 登录
 */
export function onlogin(){
  let _this = this;
  return new Promise((resolve, reject) => {    
    let header = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-Requested-With': 'XMLHttpRequest',
    'Program':'miniProgram',        
    "website-id": wx.getExtConfigSync().website_id,   
    }    
    wx.login({
      success(res) {
        var code = res.code;
        if (res.code) {
          wx.request({
            url: api.get_oauthLogin,
            header: header,
            data: { 'code': code, 'type': 'MP', },
            method: 'POST',
            success: function (res) {
              if(res.data.code == 1){
                if (getApp().userTokenEvent == '') {
                  wx.setStorageSync("user_token", res.data.data.user_token)
                  getApp().userToken = res.data.data.user_token;
                } else {
                  getApp().userToken = getApp().userTokenEvent;
                }
                let token = 'user-token';
                getApp().header[token] = getApp().userToken
                                
                wx.setStorageSync("have_mobile", res.data.data.have_mobile);
                wx.setStorageSync("openid", res.data.data.openid);
                var setCookie = res.header['Set-Cookie'];
                wx.setStorageSync("setCookie", setCookie.split(";")[0])
                getApp().header.Cookie = setCookie.split(";")[0];
                getApp().loginStatus = true;
              } else if (res.data.code == 2){
                wx.showModal({
                  title: '提示',
                  content: res.data.message,
                  success(res){
                    if(res.confirm){
                      wx.switchTab({
                        url: '/pages/member/index',
                      })
                    }
                  }
                })
              }else if(res.data.code == 3){
                wx.showModal({
                  title: '提示',
                  content: res.data.message,
                  showCancel:true,
                })
              } else if (res.data.code == 5){
                var setCookie = res.header['Set-Cookie'];
                wx.setStorageSync("setCookie", setCookie.split(";")[0])
                getApp().header.Cookie = setCookie.split(";")[0];
                loginAgain(res.data.data);
              }else{
                wx.showModal({
                  title: '提示',
                  content: '接口错误，授权登录失败',
                  showCancel: false,
                })
              }              
              resolve(res);
            },
          })
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      }
    })
  })
}

function loginAgain(rData){
  const that = this;
  let postData = {   
    'type': 'MP', 
    "extend_code": wx.getStorageSync('higherExtendCode'), 
    "encrypted_data": wx.getStorageSync('encrypted_data'), 
    "iv": wx.getStorageSync('iv'),
  }
  let header = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-Requested-With': 'XMLHttpRequest',
    'Program': 'miniProgram',
    'Cookie': wx.getStorageSync('setCookie'), 
    "website-id": wx.getExtConfigSync().website_id,
  }
  let datainfo = requestSign.requestSign(postData);
  header.sign = datainfo;
  wx.request({
    url: api.get_oauthLogin,
    data: postData,
    header: header,
    method: 'POST',
    dataType: 'json',
    responseType: 'text',
    success: (res) => {
      if (res.data.code == 1) {
        if (getApp().userTokenEvent == '') {
          wx.setStorageSync("user_token", res.data.data.user_token)
          getApp().userToken = res.data.data.user_token;
        } else {
          getApp().userToken = getApp().userTokenEvent;
        }
        let token = 'user-token';
        getApp().header[token] = getApp().userToken;

        let configData = getApp().globalData.config;
        if (getApp().globalData.no_check_phone === 0) {
          wx.setStorageSync("have_mobile", true);
        } else {
          wx.setStorageSync("have_mobile", res.data.data.have_mobile);
        }        
        
        wx.setStorageSync("openid", res.data.data.openid);        
        getApp().loginStatus = true;
      } else if (res.data.code == 2) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/member/index',
              })
            }
          }
        })
      } else if (res.data.code == 3) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel: true,
        })
      }else {
        wx.showModal({
          title: '提示',
          content: '接口错误，授权登录失败',
          showCancel: false,
        })
      }    
    },
    fail: (res) => { },
  })
}












